package com.example.friend.manager;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.core.constants.CacheConstants;
import com.example.common.core.enums.ResultCode;
import com.example.common.redis.service.RedisService;
import com.example.friend.domain.question.Question;
import com.example.friend.mapper.question.QuestionMapper;
import com.example.security.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class QuestionCacheManager {
    @Autowired
    RedisService redisService;

    @Autowired
    QuestionMapper questionMapper;

    /**
     * 获取列表大小
     * @return
     */
    public Long getListSize() {
        return redisService.getListSize(CacheConstants.QUESTION_LIST);
    }


    public void refreshCache() {
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>()
                .select(Question::getQuestionId)
                .orderByDesc(Question::getCreateTime));

        List<Long> questionIdList = questionList.stream()
                .map(Question::getQuestionId)
                .collect(Collectors.toList());
        redisService.rightPushAll(CacheConstants.QUESTION_LIST, questionIdList);
    }

    public Long preQuestion(Long questionId) {
        /**
         * 还有一种思路是把缓存的所有数据加载到java List中
         */
        Long index = redisService.indexOfForList(CacheConstants.QUESTION_LIST, questionId);
        if(index == 0) {
            throw new ServiceException(ResultCode.FAILED_FIRST_QUESTION);
        }
        return redisService.indexForList(CacheConstants.QUESTION_LIST, index - 1, Long.class);
    }

    public Long nextQuestion(Long questionId) {
        Long index = redisService.indexOfForList(CacheConstants.QUESTION_LIST, questionId);
        //判断是否已经是最后一题
        if(index == redisService.getListSize(CacheConstants.QUESTION_LIST) - 1) {
            throw new ServiceException(ResultCode.FAILED_LAST_QUESTION);
        }
        return redisService.indexForList(CacheConstants.QUESTION_LIST, index + 1, Long.class);
    }
}
